package com.pine.dcts.auth.service;


import com.pine.app.module.security.core.common.enums.ErrorType;
import com.pine.app.module.security.core.userdetails.UserDetails;
import com.pine.app.module.security.oauth.exception.AuthenticationException;
import com.pine.app.module.security.oauth.user.IntegrationLoginRequest;
import com.pine.dcts.auth.verfivation.VerificationCodeCache;
import com.pine.dcts.common.DctsConstant;
import com.pine.dcts.common.DctsException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 集成验证码认证
 * @author XYJXUST
 * @date 2018-3-31
 **/
@Component
public class VerificationCodeIntegrationAuthenticator extends UsernamePasswordAuthenticatorImpl {

    private final static String VERIFICATION_CODE_AUTH_TYPE = "vc";

    @Autowired
    private VerificationCodeCache codeClient;


    @Override
    public UserDetails authenticate(IntegrationLoginRequest integrationAuthentication) {
        if(StringUtils.isEmpty(integrationAuthentication.getUsername())
                || StringUtils.isEmpty(integrationAuthentication.getAuthParameter("password"))){

            throw new AuthenticationException(ErrorType.SERVICE_ERROR,"账号或者密码不能为空");
        }
        String vcCode = integrationAuthentication.getAuthParameter("code");
        String vcToken = integrationAuthentication.getAuthParameter("uuid");
        if(StringUtils.isEmpty(vcCode)){
            throw new AuthenticationException(ErrorType.SERVICE_ERROR,"验证码不能为空");
        }
        if(StringUtils.isEmpty(vcToken)){
            throw new AuthenticationException(ErrorType.SERVICE_ERROR,"验证token不能为空");
        }
//        //验证验证码
        if(codeClient.isExpire(DctsConstant.VERIFICATION_CODE_CACHE_NAME,vcToken)){
            throw new AuthenticationException(ErrorType.SERVICE_ERROR,"验证码过期，请重新刷新填写！");
        }
        if(!codeClient.validate(DctsConstant.VERIFICATION_CODE_CACHE_NAME,vcToken,vcCode)){
            throw new DctsException("验证码错误");
        }
        //校验逻辑
        return super.authenticate(integrationAuthentication);
    }

    @Override
    public boolean support(IntegrationLoginRequest integrationAuthentication) {
        return VERIFICATION_CODE_AUTH_TYPE.equals(integrationAuthentication.getAuthType());
    }
}
